package com.digitalchina.lxnsy.activity.old;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import androidx.recyclerview.widget.GridLayoutManager;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.digitalchina.lxnsy.R;
import com.digitalchina.lxnsy.adapter.VideoTypeAdapter;
import com.digitalchina.lxnsy.api.BusinessTrainingVideo;
import com.digitalchina.lxnsy.base.BaseActivity;
import com.digitalchina.lxnsy.constant.MSG;
import com.digitalchina.lxnsy.entity.TrainingListVO;
import com.digitalchina.lxnsy.entity.VideoOptsVO;
import com.digitalchina.lxnsy.toolkit.FastJsonUtil;
import com.digitalchina.lxnsy.toolkit.GotoUtil;
import com.digitalchina.lxnsy.toolkit.StringUtil;
import com.digitalchina.lxnsy.toolkit.Utils;
import com.digitalchina.lxnsy.viewholder.TechnologyTrainingVideoListV2Holder;
import com.jude.easyrecyclerview.EasyRecyclerView;
import com.jude.easyrecyclerview.adapter.BaseViewHolder;
import com.jude.easyrecyclerview.adapter.RecyclerArrayAdapter;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;

public class TechnologyTrainingVideoSearchActivity extends BaseActivity implements RecyclerArrayAdapter.OnLoadMoreListener, SwipeRefreshLayout.OnRefreshListener {

    @Bind(R.id.technology_video_list_search)
    EditText technologyVideoListSearch;
    @Bind(R.id.recycler_view)
    EasyRecyclerView recyclerView;
    @Bind(R.id.technology_video_list_iv_menu)
    ImageView technologyVideoListIvMenu;
    @Bind(R.id.technology_video_lv_type)
    ListView technologyVideoLvType;
    @Bind(R.id.technology_video_drawer_layout)
    DrawerLayout technologyVideoDrawerLayout;

    private RecyclerArrayAdapter adapter;
    private int page = 1;
    private int limit = 10;
    private List<TrainingListVO> trainingListVO = new ArrayList<>();
    private String keyWords = "";
    private String code = "";

    private VideoTypeAdapter videoTypeAdapter;

    @Override
    public void setLayout() {
        setTitle("视频搜索");
        setContentLayout(R.layout.activity_technology_training_video_list);
    }

    @Override
    public void initMember() {


        // 获取视频分类
        //BusinessTrainingVideo.getVideoOpts(this, mHandler);


        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 2);
        recyclerView.setLayoutManager(gridLayoutManager);
        recyclerView.addItemDecoration(Utils.setDividerDecoration(this, 1, 0, 0));
        recyclerView.setAdapterWithProgress(adapter = new RecyclerArrayAdapter(this) {
            @Override
            public BaseViewHolder OnCreateViewHolder(ViewGroup parent, int viewType) {
                return new TechnologyTrainingVideoListV2Holder(parent);
            }
        });

        gridLayoutManager.setSpanSizeLookup(adapter.obtainGridSpanSizeLookUp(2));

        onRefresh();
    }

    @Override
    public void addListener() {
        recyclerView.setRefreshListener(this);
        adapter.setMore(R.layout.view_more, this);
        adapter.setNoMore(R.layout.view_nomore);
        adapter.setError(R.layout.view_error, new RecyclerArrayAdapter.OnErrorListener() {
            @Override
            public void onErrorShow() {
                adapter.resumeMore();
            }

            @Override
            public void onErrorClick() {
                adapter.resumeMore();
            }
        });

        adapter.setOnItemClickListener(new RecyclerArrayAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                TrainingListVO item = (TrainingListVO) adapter.getAllData().get(position);
               /* if(item.getVideoType().getCode().equals("1516")){
                    Map<String, String> map = new HashMap<>();
                    map.put("url",item.getLiveAddress());
                    map.put("title","专家直播");
                    GotoUtil.gotoActivity(TechnologyTrainingVideoSearchActivity.this, WebViewActivity.class, "map", map);
                }else{
                    if (!StringUtil.isStrEmpty(item.getVideoSign()) && item.getVideoSign().equals("1"))
                        GotoUtil.gotoActivity(TechnologyTrainingVideoSearchActivity.this, TechnologyTrainingVideoDetailNewActivity.class, "path", item.getPlayUrl());
                    else
                        GotoUtil.gotoActivity(TechnologyTrainingVideoSearchActivity.this, TechnologyTrainingVideoDetailNewActivity.class, "TrainingListVO", item);
                }*/
                GotoUtil.gotoActivity(TechnologyTrainingVideoSearchActivity.this, TechnologyTrainingVideoDetailNewActivity.class, "TrainingListVO", item);
            }
        });

        technologyVideoListSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int actionId, KeyEvent keyEvent) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    // 隐藏软键盘
                    InputMethodManager imm = (InputMethodManager) textView
                            .getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                    if (imm.isActive()) {
                        imm.hideSoftInputFromWindow(textView.getApplicationWindowToken(), 0);
                    }
                    // 刷新列表数据
                    if (!keyWords.equals(technologyVideoListSearch.getText().toString())) {
                        keyWords = technologyVideoListSearch.getText().toString();
                        onRefresh();
                    }
                    return true;
                }
                return false;
            }
        });

        technologyVideoListIvMenu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                technologyVideoDrawerLayout.openDrawer(GravityCompat.START);
            }
        });

        technologyVideoLvType.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                videoTypeAdapter.setSelectPosition(position);
                videoTypeAdapter.notifyDataSetChanged();
                if (videoTypeAdapter.getItem(position).getValue().equals("-1")) {
                    keyWords = "";
                    code = "";
                    technologyVideoListSearch.setText("");
                } else {
                    code = videoTypeAdapter.getItem(position).getValue();
                }
                onRefresh();
                technologyVideoDrawerLayout.closeDrawer(GravityCompat.START);
            }
        });
    }

    @Override
    public void setHandler() {
        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);

                if (recyclerView == null) {
                    return;
                }
                if (recyclerView.getSwipeToRefresh().isRefreshing())
                    recyclerView.setRefreshing(false);

                switch (msg.what) {
                    case MSG.MSG_TRAINING_SAVE_SUCCESS:
                        callBack(msg.obj);
                        break;
                    case MSG.MSG_TRAINING_SAVE_FIELD:
                        showToast(msg.obj.toString());
                        break;
                }
            }
        };
    }


    /**
     * 设置左侧分类
     *
     * @param obj
     */
    private void setLeftView(Object obj) {

        List<VideoOptsVO> voList = FastJsonUtil.getListBean(obj.toString(), "body", "opts", VideoOptsVO.class);
        if (voList != null) {
            VideoOptsVO vo = new VideoOptsVO();
            vo.setValue("-1");
            vo.setLabel("全部");
            voList.add(0, vo);
            videoTypeAdapter = new VideoTypeAdapter(this, voList);
            videoTypeAdapter.setSelectPosition(0);
            technologyVideoLvType.setAdapter(videoTypeAdapter);
        }
    }


    @Override
    public void callBack(Object object) {
        trainingListVO = FastJsonUtil.getListBeanRow(object.toString(), "rows", TrainingListVO.class);
        if (page == 1) { // 刷新
            adapter.clear();
        }



        if (trainingListVO != null) {
            if (trainingListVO.size() < limit) {
                adapter.stopMore();
            }
        }


        adapter.addAll(trainingListVO);
    }

    @Override
    public void onRefresh() {
        page = 1;
        BusinessTrainingVideo.getTrainingVideoList(this, String.valueOf(page), String.valueOf(limit), code, keyWords,"1", mHandler);
    }

    @Override
    public void onLoadMore() {
            page++;
            BusinessTrainingVideo.getTrainingVideoList(this, String.valueOf(page), String.valueOf(limit), code, keyWords,"1", mHandler);
    }

    @Override
    public void rightOnClick() {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (technologyVideoDrawerLayout.isDrawerVisible(GravityCompat.START)) {
                technologyVideoDrawerLayout.closeDrawer(GravityCompat.START);
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }
}
